package com.bjfu.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bjfu.demo.dto.StatisticRawResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NewStatisticServiceImpl {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public List<StatisticRawResult> getStatisticByYear() {
        return getStatistic("rp:AllStatisticResultByYear");
    }

    public List<StatisticRawResult> getStatisticBySeason() {
        return getStatistic("rp:AllStatisticResultBySeason");

    }


    public List<StatisticRawResult> getStatisticByMonth() {
        return getStatistic("rp:AllStatisticResultByMonth");
    }


    private List<StatisticRawResult> getStatistic(String period) {
        String allStatisticResultByMonthJson = stringRedisTemplate.opsForValue().get(period);
        List<StatisticRawResult> statisticRawResults = JSON.parseObject(allStatisticResultByMonthJson, new TypeReference<List<StatisticRawResult>>() {
        });
        for (StatisticRawResult statisticRawResult : statisticRawResults) {
            StatisticRawResult stationInfo = getStationByCode(statisticRawResult.getSiteCode());
            if (stationInfo != null) {
                statisticRawResult.setSiteName(stationInfo.getSiteName());
                statisticRawResult.setDistrict(stationInfo.getDistrict());
            }

        }
        return statisticRawResults.stream().filter(s -> s.getSiteName() != null).collect(Collectors.toList());
    }

    public StatisticRawResult getStationByCode(String code) {
        String allStationInfoJson = stringRedisTemplate.opsForValue().get("rp:AllStationInfo");
        HashMap<String, StatisticRawResult> stationMap = JSON.parseObject(allStationInfoJson, new TypeReference<HashMap<String, StatisticRawResult>>() {
        });
        if (stationMap != null) {

            return stationMap.get(code.toUpperCase());
        }
        return null;
    }
}
